use std::{thread::sleep, time::Duration};

use model_graph_peer::{assistant::assistant_local_chat, data_channels::message::Message};
use model_graph_types::assistant::chat::{ChatMessage, ChatOptions};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::DEBUG)
        .init();
    tracing::info!("RRAI 启动...");

    let v: Vec<u8> = Message::ping().try_into()?;
    tracing::debug!("{}", Message::try_from(v).unwrap());

    let token = String::from("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOiI1OTEyMDg4ZTQ4YmM0MGFjODQ2MjJiMzMwZTg0MTc1ZiIsInVuaW9uaWQiOiJvbXVSV3c4N2w1Q3ZacVhaZmFTbmVzRnVXZVBvIiwib3BlbmlkIjoib2VDTEo1a0FkM0d5RnN2bDhRWWF0WTZIS3RzRSIsImV4cCI6MTcxMDgxNDU5MTMwN30.eXKKXqklU0W9vKH1xuHqNu37clEbeqpebfF17jg1zZY");

    let _ = model_graph_peer::peer_start().await;

    let result = model_graph_peer::peer_login(&token).await;

    match result {
        Ok(result) => {
            tracing::debug!("!!!!!!{:?}", result);
        }
        Err(err) => tracing::debug!("===-----{:?}", err),
    }

    sleep(Duration::from_secs(5));
    //
    // let remote_peer_id = String::from("12D3KooWHPmbPfhhovuMp1dS3qwemSQn7iWJEu2a64Rh2DHHzmgE");
    let remote_peer_id = String::from("12D3KooWBzNmYjd9Ac5AtGFWEC6ukufNXQYubG8djWvqWQwgRwHv");

    //
    let result = model_graph_peer::transport::prepare_follower(&remote_peer_id).await;

    match result {
        Ok(_) => {
            tracing::debug!("prepare_follower_channel 成功！");
        }
        Err(err) => tracing::debug!("===-----{:?}", err),
    }

    sleep(Duration::from_secs(10));

    // let mut message: Message = Message::default();
    // message.data = "test".as_bytes().to_vec();

    // let result =
    //     model_graph_peer::data_channels::request::fire_and_forget(&remote_peer_id, message).await;
    // match result {
    //     Ok(_) => {
    //         tracing::debug!("fire_and_forget 成功！");
    //     }
    //     Err(err) => tracing::debug!("===-----{:?}", err),
    // }

    for _ in 0..20 {
        let messages = vec![ChatMessage::user(String::from("你是谁？"))];
        let result = assistant_local_chat(messages, ChatOptions::new()).await;
        match result {
            Ok(response) => {
                tracing::debug!("request_response 成功！{:?}", response);
            }
            Err(err) => tracing::debug!("===-----{:?}", err),
        }
    }

    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            println!();
        }
    };
    tracing::info!("RRAI 结束...");
    Ok(())
}
